package com.example.demo.handler;

import com.example.demo.common.R;
import com.example.demo.exception.BusinessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
    public ResponseEntity<Map<String, String>> handleValidationException(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error -> {
            errors.put(error.getField(), error.getDefaultMessage());
        });
        return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED.value()).body(errors);
    }

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<R> handleBusinessException(BusinessException e) {
        R<Void> r = new R<>(e.getCode(), e.getMessage());
        return ResponseEntity.status(r.getCode()).body(r);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
    public ResponseEntity<R> handleBusinessException(Exception e) {
        R<Void> r = new R<>(HttpStatus.NOT_IMPLEMENTED.value(), e.getMessage());
        return ResponseEntity.status(r.getCode()).body(r);
    }
}
